#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "MSTK.h"


int main(int argc, char *argv[]) {
  int k, len, suff, ok;
  char mname[256], filename[256];
  Mesh_ptr mesh;
  /* default divide into two parts */
  int num = 2;
  int verbose = 0;
  /* command line parameter */
  
  if (argc == 1) {
    fprintf(stdout, "meshcat concatenats the submeshes into a global mesh\n");
    fprintf(stdout, "Usage: meshcat -n 4 filename\n");
    fprintf(stdout, "Output: submeshes in mstk and pmstk format\n");
    fprintf(stdout, "Option: -h for help\n");
    fprintf(stdout, "        -n number of partition\n");
    return -1;
  }
  argc--;
  argv++;
    
  while (argc >= 1)
    {
      if (argv[0][0] == '-') {	
	switch(argv[0][1]) {
	case 'h':
	case 'H':
	  fprintf(stdout, "meshcat concatenats the submeshes into a global mesh\n");
	  fprintf(stdout, "Usage: meshcat -n 4 filename\n");
	  fprintf(stdout, "Output: submeshes in mstk and pmstk format\n");
	  fprintf(stdout, "Option: -h for help\n");
	  fprintf(stdout, "        -n number of partition\n");
   	  argc -= 1;
          argv += 1;
	  return -1;
	  break;
	case 'n':
	case 'N':
	  num = atoi(argv[1]);
	  argc -= 2;
	  argv += 2;
          break;
	case 'v':
	case 'V':
	  verbose = 1;
	  argc -= 1;
	  argv += 1;
	  break;
	}
      }
      else {
	strcpy(mname,argv[0]);
	argc -= 1;
	argv += 1;
      }
    }
 


  /* Initialize MSTK - Always do this even if it does not seem to
     matter in this version of MSTK */

  MSTK_Init();

  /* Load the mesh */

  len = strlen(mname);
  suff = 0;
  if (len > 5) {
    k = len-5;
    while (!suff && k > 1) {
      if (strncmp(&(mname[k]),".mstk",5) == 0) {
        suff = 1;
      }
      else
        k--;
    }
  }
  if (suff)
    mname[len-5] = '\0';

  strcpy(filename,mname);
  strcat(filename,".mstk");

  mesh = MESH_New(UNKNOWN_REP);
  ok = MESH_InitFromFile(mesh,filename);
  if (!ok) {
    fprintf(stderr,"Cannot open input file %s\n\n\n",filename);
    exit(-1);
  }
  fprintf(stdout,"mstk mesh %s read in successfully\n",filename);
  RepType rtype = MESH_RepType(mesh);
  /* Partition the mesh*/

  Mesh_ptr *submeshes = (Mesh_ptr *)MSTK_malloc(num*sizeof(Mesh_ptr));
  
  MSTK_Mesh_Partition(mesh,submeshes,num,0,1);
  fprintf(stdout,"%s has been partitioned into %d submeshes\n",filename,num);


  char subfilename[256];

  /* Concatenate */
  Mesh_ptr new_mesh = MESH_New(UNKNOWN_REP);
  MSTK_Mesh_Concatenate(new_mesh,submeshes,num,1);
  fprintf(stdout,"global mesh has been concatenated \n");
  strcpy(subfilename,mname);
  strcat(subfilename,"-P-global.mstk");
  PMESH_WriteToFile(new_mesh,subfilename,rtype);
  fprintf(stdout,"global mesh has been written into %s\n",subfilename);

  fprintf(stdout,"global mesh has been concatenated \n");
  strcpy(subfilename,mname);
  strcat(subfilename,"-P.mstk");
  PMESH_WriteToFile(mesh,subfilename,rtype);
  fprintf(stdout,"original mesh has been written into %s\n",subfilename);

  return 1;
}

